package com.itheima.reggie.web;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.service.ICategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    ICategoryService iCategoryService;

    /**
     * 新增分类
     * @param category
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody Category category){
        log.info("category:{}",category);
        iCategoryService.save(category);
        return R.success("新增成功");
    }

    /**
     * 分页查询
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(Integer page, Integer pageSize){
        //分页构造器
        Page<Category> CategoryPage = new Page<>(page,pageSize);
        //条件构建器
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        //添加排序条件,根据sort进行排序
        queryWrapper.orderByAsc(Category::getSort);
        //分页查询
        iCategoryService.page(CategoryPage,queryWrapper);

        return R.success(CategoryPage);
    }

    /**
     * 根据id修改分类信息
     * @param category
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody Category category){
        log.info("修改分类信息:{}",category);
        iCategoryService.updateById(category);
        return R.success("修改分类信息成功");
    }

    /**
     * 根据id进行删除
     * @param id
     * @return
     */
    @DeleteMapping
    public R<String> deleteById(Long id){
        Boolean result=iCategoryService.deleteById(id);
        return result?R.success("删除成功"):R.error("无法删除分类,当前分类下存在菜品或者套餐");

    }

    /**
     * 根据条件查询分类数据
     * @param type
     * @return
     */
    @GetMapping("/list")
    public R<List<Category>> query(Integer type){
        LambdaQueryWrapper<Category> categoryLambdaQueryWrapper = new LambdaQueryWrapper<>();
        categoryLambdaQueryWrapper.eq(type!=null,Category::getType,type);

        List<Category> list = iCategoryService.list(categoryLambdaQueryWrapper);

        return R.success(list);
    }

}
